<?php
namespace App\Model\Backstage;
use App\Model\Base;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

/**
 * Class Department
 * @package App\Model\Backstage
 *公司对应部门model
 * date:2018-4-30
 * author :lxy
 */
class Department extends Base
{
    /**
     * @param array $map 查找的条件
     * @param string $order  排序方式
     */
    protected $table = 'department';

    /**
     * @param array $map
     * @return mixed
     * 获取部门列表
     */
    public function getDepartmentList($map = [])
    {
        return $this->where($map)->where('c_id', $this->branch_id)->orderBy('id','desc')->get();
    }

    /**
     * @param $params
     * @return mixed
     * 添加公司对应部门
     */
    public function addDepartment ($params)
    {
        $params['c_id'] = $this->branch_id;
        $params['created_at'] = time();
        return $this->insert($params);
    }

    /**
     * @param $params
     * @return mixed
     * 修改部门信息
     */
    public function saveDepartment ($params)
    {
        $params['updated_at'] = time();
        return $this->where(['id' => $params['id']])->update($params);
    }

    /**
     * @param $user
     * @param $d_id
     * @return array
     * 删除部门信息 判断部门下面是否有用户
     */
    public function delDepartment($d_id)
    {
        $list = DB::table('user')->where('u_d_id', $d_id)->where('is_del', 0)->value('u_id');  //查找是否有用户
        if(!$list){
            $res = $this->where(['id'=>$d_id])->update(['is_del' => 1, 'updated_at' => time()]);
            if($res){
                return ['code' => 0, 'msg' => '删除成功'];
            }else{
                return ['code' => 1, 'msg' => '删除失败'];
            }
        }else{
            return ['code' => 1, 'msg' => '此部门下面还有用户，请先删除用户'];
        }

    }


    /**获取中介公司下面的部门列表
     * @param array $map
     * @return mixed
     */
    public function getDropdown($map =[])
    {
        return $this->where($map)->where('c_id', $this->branch_id)->select('id', 'name')->get();
    }


    /**
     * 获取部门下面员工的列表
     */
    public  function downList($where)
    {
        return DB::table('user')->where('u_b_id', $this->branch_id)->where($where)->select('u_id', 'u_username')->get();
    }
}